package com.yn.common.config.web;

import com.yn.common.utils.ex.BaseErrorEnum;
import com.yn.common.utils.ex.BusinessException;
import com.yn.common.utils.web.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

/**
 * @description: 统一异常处理
 * @author: zq
 * @create: 2022/3/29 11:00
 * @since: 1.0.0
 * @copyright (C), 2020, 北京望海康信科技有限公司.All rights reserved.
 */
@RestControllerAdvice(basePackages = "com.yn", annotations = {Controller.class, RestController.class})
@Slf4j
public class WebExceptionHandler {

    //处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常，详情继续往下看代码
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public R argsExceptionHandler1(BindException e) {
        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
        return R.error().code(BaseErrorEnum.CHECK_PARAMS_ERR.getCode()).message(message);
    }

    /**
     * 处理请求参数格式错误
     * 注意：在使用时需要在Controller上添加注解@Validated
     * 参见：com.viewhigh.data.mc.web.std.StdDicMaterialController#delete(java.util.List)
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public R argsExceptionHandler2(ConstraintViolationException e) {
        String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
        return R.error().code(BaseErrorEnum.CHECK_PARAMS_ERR.getCode()).message(message);

    }

    /**
     * 对象参数（对象中存在待校验内容）校验异常
     * 处理请求参数格式错误 @RequestBody上validate失败后抛出的异常是MethodArgumentNotValidException异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R argsExceptionHandler3(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
//            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
//            for(FieldError err:fieldErrors){
//                System.out.println(err);
//            }
        //返回第一个错误的信息
        String defaultMessage = bindingResult.getFieldError().getDefaultMessage();
        return R.error().code(BaseErrorEnum.CHECK_PARAMS_ERR.getCode()).message(defaultMessage);
    }

    /**
     * 业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler({BusinessException.class, Exception.class})
    public R businessExceptionHandler(Exception e) {
        if (e instanceof BusinessException) {
            BusinessException biz = (BusinessException) e;
            return R.error().code(biz.getCode()).message(biz.getMessage());
        } else {
            // 判断是不是es索引未创建导致的错误
            if (e.getMessage().equals("Elasticsearch exception [type=index_not_found_exception, reason=no such index]")) {
                return R.error().message("当前项目对应的索引未创建");
            }
            e.printStackTrace();
            log.error(e.getMessage());
            return R.error();
        }
    }
}
